<!--
 * @Author: Yang Zhang
 * @Date: 2021-11-27 12:20:24
 * @LastEditors: Yang Zhang
 * @LastEditTime: 2021-12-23 16:33:38
 * @Description: 登录的弹窗组件
-->
<template>
  <div class="kol-auth-modal" @mousewheel="mousewheel" v-if="modalShow">
    <div class="modalInfo">
      <close-outlined @click.stop="modalShow = !modalShow" class="close" />
      <div class="modal-title">{{ modalTitle }}</div>
      <div class="modal-desc">{{ modalDesc }}</div>
      <div class="form">
        <a-form
          layout="horizontal"
          :model="formState"
          @finish="handleFinish"
          @finishFailed="handleFinishFailed"
        >
          <a-form-item>
            <a-input
              v-if="type === 0"
              v-model:value="formState.username"
              placeholder="*Email address"
            ></a-input>
            <a-input v-else v-model:value="formState.email" placeholder="*Email address"></a-input>
          </a-form-item>
          <a-form-item>
            <a-input-password v-model:value="formState.password" placeholder="Input password" />
          </a-form-item>
          <a-form-item v-if="type === 1">
            <a-input v-model:value="formState.code" placeholder="*Verification code">
              <template #suffix>
                <div class="sendBtn" @click.stop="sendEmailVercode">{{ btntxt || btnnum }}</div>
              </template>
            </a-input>
          </a-form-item>
          <a-form-item class="verFormItem" v-if="type === 1">
            <verify
              ref="verifyRef"
              class="verify-content"
              :verifyType="verType"
              @change="verifyChange"
            ></verify>
            <div
              class="verBtn"
              :class="verFormItem ? 'vertedBtn' : ''"
              @click.stop="openVerslider"
            >Click Complete Security Verification</div>
          </a-form-item>
          <a-form-item class="verFormItem">
            <verify
              ref="verifyLoginRef"
              class="verify-content"
              verifyType="LOGIN"
              @change="verifyLoginChange"
              v-if="type === 0"
            ></verify>
            <a-button
              type="primary"
              v-if="type === 0"
              html-type="submit"
              :disabled="formState.username === '' || formState.password === ''"
            >Log in</a-button>
            <a-button
              type="primary"
              v-else
              html-type="submit"
              :disabled="formState.email === '' || formState.password === '' || formState.code === ''"
            >Sign up</a-button>
          </a-form-item>
        </a-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { reactive, toRefs, onBeforeMount, onMounted, ref, UnwrapRef, defineComponent, PropType } from 'vue'
import { FormProps, message } from 'ant-design-vue'
import verify from '../../../components/SliderVer/index.vue'
import { sendEmailVernum } from '../../../api/common'
import { userLogin, userRegi } from '../../../api/app'
import md5 from 'js-md5'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { CloseOutlined } from '@ant-design/icons-vue'
export default defineComponent({
  name: 'AuthModal',
  components: {
    verify, CloseOutlined
  },
  props: {
    type: {
      type: Number,
      default: 0   // 0为登录 1 为注册
    }
  },
  setup(props) {
    const { type } = toRefs(props)
    const modalTitle = ref('')
    const modalDesc = ref('')
    const verType = ref('')
    const store = useStore()
    const router = useRouter()
    onMounted(() => {
      modalTitle.value = type.value === 0 ? 'LOG IN' : 'SIGN UP'
      modalDesc.value = type.value === 0 ? 'To access your account' : 'Create an account'
      verType.value = type.value === 0 ? 'LOGIN' : 'REGISTER'
    })


    const verFormItem = ref(false) // 是否通过图片滑块验证
    /**
     * 
     * @description 开启滑块验证
     */
    const verifyRef = ref()
    const openVerslider = () => {
      verifyRef.value.init()
    }

    const verifyChange = (text: any) => {
      if (!text.status) return
      verFormItem.value = text.status
      verifyRef.value.show = false
    }



    const sendEmailVercode = async () => {
      if (!verFormItem.value) {
        verifyRef.value.init()
      } else {
        btntxt.value = ''
        const timer = setInterval(() => {
          if (btnnum.value === 1) {
            clearInterval(timer)
            btntxt.value = 'send'
            btnnum.value = 60
          }
          btnnum.value = btnnum.value - 1
          console.log(btnnum.value)
        }, 1000)
        let param = {
          verificationEnums: 'REGISTER',
          email: formState.email
        }
        const res = await sendEmailVernum(param)
        console.log(res)
      }
    }




    // 防止出现遮罩层底部还会滑动
    const mousewheel = (e: { preventDefault: () => void; }) => {
      e.preventDefault()
    }


    const modalShow = ref(false)

    const closeModal = (e: { currentTarget: any; target: any; }) => {
      modalShow.value = !(e.currentTarget == e.target)
    }
    const showLoginModal = () => {
      modalShow.value = !modalShow.value
    }

    // about form
    interface FormState {
      username?: string;
      email?: any;
      password: string;
      code?: string
    }
    const formState: UnwrapRef<FormState> = reactive({
      username: '',
      password: '',
      email: '',
      code: ''
    });
    const handleFinish = async (values: any) => {
      if (type.value === 0) {
        verifyLoginRef.value.init()
      } else {
        let param = {
          email: formState.email,
          code: formState.code,
          password: md5(formState.password)
        }
        const res = await userRegi(param)
        console.log(res)
        if (res && res.code === 200) {
          store.dispatch('user/updateAccessToken', res.result.accessToken)
          store.dispatch('user/updateRefreshToken', res.result.refreshToken)
          showLoginModal()
          router.push({ path: '/kol/index/editStore', replace: true })
        } else {
          showLoginModal()
        }
      }

    };
    const handleFinishFailed = (errors: any) => {
      console.log(errors);
    };


    // 登陆相关的滑块验证
    const verifyLoginRef = ref()    // 登录的滑块组件的ref实例
    const verifyLoginStatus = ref(false)
    const verifyLoginChange = async (text: any) => {
      if (!text.status) return
      verifyLoginStatus.value = text.status
      let param = {
        username: formState.username,
        password: md5(formState.password)
      }
      const res = await userLogin(param)
      console.log(res)
      if (res && res.code === 200) {
        store.dispatch('user/updateAccessToken', res.result.accessToken)
        store.dispatch('user/updateRefreshToken', res.result.refreshToken)
        showLoginModal()
        router.push({ path: '/kol/index', replace: true })
      } else {
        verifyLoginRef.value.show = false
        showLoginModal()
      }
      verifyLoginRef.value.show = false
    }



    const btntxt = ref('send')
    const btnnum = ref(60)
    return {
      verifyLoginRef, verifyLoginChange, btntxt, btnnum,
      verType, sendEmailVercode, verifyRef, verifyChange, verFormItem, mousewheel, modalShow, openVerslider, closeModal, showLoginModal, formState, handleFinish, handleFinishFailed, modalTitle, modalDesc
    }

  }
})


</script>

<style lang='scss' scoped>
.kol-auth-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  .modalInfo {
    width: 837px;
    background-color: #fff;
    text-align: center;
    padding: 90px 138px;
    border-radius: 10px;
    position: relative;
    svg {
      width: 3em;
      height: 3em;
    }
    .close {
      width: 3em;
      height: 3em;
      position: absolute;
      top: 4em;
      right: 2em;
      cursor: pointer;
      svg {
        width: 3em;
        height: 3em;
      }
    }
    .modal-title {
      font-size: 36px;
      font-family: Galvji;
      font-weight: 400;
      color: #070023;
    }
    .modal-desc {
      font-size: 24px;
      font-family: Galvji;
      font-weight: 400;
      color: #757575;
      margin-bottom: 63px;
    }
    .ant-input,
    .ant-input-password {
      height: 90px;
      font-size: 24px;
      font-family: Galvji;
      font-weight: 400;
      color: #757575;
      border: 2px solid #e0e0e0;
      border-radius: 10px;
      input.ant-input {
        font-size: 24px;
      }
    }
    .ant-input-affix-wrapper {
      .ant-input {
        height: 90px;
      }
    }
    .ant-input:focus {
      border-color: #e60044;
      box-shadow: none;
    }
    .ant-input-affix-wrapper:hover,
    .ant-input-affix-wrapper:focus {
      border-color: #e60044;
      box-shadow: none;
    }
    .ant-input-group-wrapper {
      height: 90px;
      .ant-input-group {
        height: 90px;
        input {
          height: 90px;
        }
      }
    }

    .ant-form-item:last-child {
      margin-top: 80px;
    }

    .ant-btn {
      width: 562px;
      height: 69px;
      background: #e60044;
      border-radius: 33px;
      color: #fff;
      font-size: 22px;
    }
    .ant-btn-primary[disabled] {
      background-color: rgba(224, 224, 224, 1);
    }
  }
}
.verBtn {
  width: 562px;
  height: 90px;
  background: rgba(224, 224, 224, 0.3);
  border: 2px solid #e0e0e0;
  border-radius: 10px;
  font-size: 24px;
  font-family: Galvji;
  font-weight: 400;
  color: #070023;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.vertedBtn {
  background: rgba(230, 0, 68, 0.1);
  border: 2px solid #e60044;
  color: #e60044;
}
.ant-input {
  height: 90px;
}
.verFormItem {
  position: relative;
}
.sendBtn {
  border-left: 1px solid #e0e0e0;
  padding-left: 37px;
  padding-right: 37px;
  cursor: pointer;
  font-size: 22px;
}
</style>
